import com.matuw.android.plugin.ProjectExtensions
import com.matuw.android.plugin.libs
import com.android.build.gradle.LibraryExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.kotlin
import com.matuw.android.plugin.configureKotlinAndroid
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class AndroidLibraryConventionPlugin : Plugin<Project> {
    override fun apply(target: Project) {
        with(target) {
            with(pluginManager) {
                apply("com.android.library")
                apply("org.jetbrains.kotlin.android")
            }

            extensions.configure<LibraryExtension> {
                configureKotlinAndroid(this)

                with(defaultConfig) {
                    targetSdk = ProjectExtensions.TARGET_SDK_VERSION
                    multiDexEnabled = true
                    consumerProguardFiles.add(file("consumer-rules.pro"))
                    version = ProjectExtensions.VERSION_NAME
                }

                testOptions.animationsDisabled = true
                buildFeatures.buildConfig = true

                buildTypes {
                    release {
                        isMinifyEnabled = true
                        proguardFiles(
                            getDefaultProguardFile("proguard-android.txt"),
                            "proguard-rules.pro"
                        )
                    }
                }

                val timestamp = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(Date())
                libraryVariants.all {
                    val flavorName = flavorName ?: ""
                    val buildType = buildType.name
                    val versionName = target.version.toString()

                    buildConfigField("String", "BUILD_TIMESTAMP", "\"${timestamp}\"")
                    buildConfigField("String", "BUILD_VERSION", "\"${versionName}\"")

                    outputs.all {
                        if (this is com.android.build.gradle.internal.api.BaseVariantOutputImpl) {
                            val filename = "Qin_${target.name}-" +
                                    (if (flavorName.isNotEmpty()) "$flavorName-" else "") +
                                    (if (buildType == "debug") "debug-" else "") +
                                    "${versionName}.aar"

                            outputFileName = filename
                        }
                    }
                }
            }
            dependencies {
                val args = mapOf("include" to arrayOf("*.jar"), "dir" to "libs")
                add("implementation", fileTree(args))
                add("implementation", libs.findLibrary("androidx.annotation").get())
                add("testImplementation", kotlin("test"))
            }
        }
    }
}
